/******************************************************************************
 * SAGE - Scalable Adaptive Graphics Environment
 *
 * Module: audioInstance.h
 * Author : Byungil Jeong, Hyejung Hur
 *
 * Copyright (C) 2004 Electronic Visualization Laboratory,
 * University of Illinois at Chicago
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either Version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser Public License along
 * with this library; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * Direct questions, comments etc about SAGE to bijeong@evl.uic.edu or 
 * http://www.evl.uic.edu/cavern/forum/
 *
 *****************************************************************************/
 
#ifndef _AUDIO_INSTANCE_H_
#define _AUDIO_INSTANCE_H_

#include "sage.h"
#include "sageSync.h"
#include "sageAudioModule.h"
#include "audioCircBuf.h"
#include "audioTcpModule.h"
#include "audioUdpModule.h"
#include "streamInfo.h"

class aStreamRcv;
class audioInstance;

class audioInstance {
public:   
	audioInstance();
	~audioInstance();

public:
	static int sailNodeNum;
	static sageSyncServer *syncServerObj;	
	static sageSyncClient *syncClientObj;

	static void* syncMasterThread(void* args);
	static void* rcvThread(void* args);

public:   
	int init(aStreamRcv *gsr, int id, audioTcpModule *protoObj, audioCircBuf *buf);

	int fetchSageBlocks();
	bool checkSyncSignal();
	int destroyInstance();
	int addStream(int sender, int instid);
	int rcvStream();

protected:	
	int sendPerformanceInfo();
	int createRcvThread(int senderID, int tileID);
	int initSyncConnection();
	int sendAckToSenders(int flag);
	int sendAckToSender(int senderID, int flag);
	int processSageBlock();

private:
	aStreamRcv *rcv;
	audioTcpModule *nwObj;

	sageAudioModule *audioObj;	
	audioCircBuf *buffer;

	sageAudioBlock audioNBlock;
	int senderID;

	int instID;	// idx
	
	int frameNum;
	int masterFrameNum;

	int syncMode;
	bool waitingSync;
	bool connectionDone;
	bool streamsUp;

	/** for performance check */
	int oldFrame;
	int reportRate;
	double reportTime;
	unsigned long bandWidth;
	unsigned packetLoss;
	double oldTime;
	////////////////
	
	bool streamStop;
	
	pthread_mutex_t *condMutex;
	pthread_cond_t  *bufReady;
	pthread_cond_t  *beginWaiting;	
	
	friend class aStreamRcv;
};

#endif
